package com.yfp.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.MachineDO;
import com.yfp.operation.domain.MealReplacementDO;
import com.yfp.operation.domain.dto.PersonalOnlineStatusDTO;
import com.yfp.operation.domain.vo.PersonalOnlineStatusVO;
import com.yfp.operation.service.MachineService;
import com.yfp.operation.service.MealReplacementService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PersonalService implements com.yfp.operation.service.PersonalService {

    @Resource
    private MachineService machineService;
    @Resource
    private MealReplacementService mealReplacementService;

    /**
     * 获取设备列表
     * 个人中心设备在线状态
     */
    @Override
    public List<PersonalOnlineStatusVO> getListState() {
        Long userId = SecurityUtils.getUserId();

        List<String> machineIds = machineService.getMachineOperationByUserId(userId).stream().map(MachineDO::getMachineId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(machineIds)) {
            // 当前用户没有与设备进行绑定，直接返回空列表
            return Collections.emptyList();
        }
        LambdaQueryWrapper<MealReplacementDO> MealReplacementQuery = Wrappers.lambdaQuery(MealReplacementDO.class);
        MealReplacementQuery.in(MealReplacementDO::getMachineId, machineIds);
        MealReplacementQuery.eq(MealReplacementDO::getUserId, userId);
        List<MealReplacementDO> mealReplacementDOS = mealReplacementService.list(MealReplacementQuery);
        mealReplacementDOS = mealReplacementDOS.stream().collect(Collectors.groupingBy(MealReplacementDO::getMachineId, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(MealReplacementDO::getId)), optional -> optional.orElse(null)))).values().stream().filter(Objects::nonNull).toList();

        List<MealReplacementDO> mealReplacementDOList = new ArrayList<>();
        mealReplacementDOList.addAll(mealReplacementDOS);

        List<String> newMachineIds = CollUtil.subtractToList(machineIds, mealReplacementDOS.stream().map(MealReplacementDO::getMachineId).collect(Collectors.toList()));
        // 如果不为空表示为新的查询，没有添加过代取信息。这里添加默认值，默认值为关闭代取
        if (CollectionUtils.isNotEmpty(newMachineIds)) {
            List<MealReplacementDO> collect = newMachineIds.stream().map(item -> {
                MealReplacementDO mealReplacementDO = new MealReplacementDO();
                mealReplacementDO.setMachineId(item);
                mealReplacementDO.setUserId(userId);
                mealReplacementDO.setStatus(0);
                return mealReplacementDO;
            }).toList();
            mealReplacementDOList.addAll(collect);
        }

        // 调整返回格式
        List<PersonalOnlineStatusVO> personalOnlineStatusVOS = BeanUtil.copyToList(mealReplacementDOList, PersonalOnlineStatusVO.class).stream().map(item -> {
            item.setStatus(BooleanUtil.toBoolean(item.getStatus().toString()));
            return item;
        }).sorted(Comparator.comparing(PersonalOnlineStatusVO::getMachineId)).toList();
        return personalOnlineStatusVOS;
    }

    /**
     * 更新设备状态
     *
     * @param personalOnlineStatusDTO@return 是否更新成功
     */
    @Transactional
    @Override
    public boolean updateState(PersonalOnlineStatusDTO personalOnlineStatusDTO) {
        Long userId = SecurityUtils.getUserId();
        DateTime date = DateUtil.date();

        // 在线状态{false：否，true：在线}
        if (personalOnlineStatusDTO.getStatus()) {
            MealReplacementDO mealReplacementDO = new MealReplacementDO();
            mealReplacementDO.setMachineId(personalOnlineStatusDTO.getMachineId());
            mealReplacementDO.setUserId(userId);
            mealReplacementDO.setStatus(BooleanUtil.toInt(personalOnlineStatusDTO.getStatus()));
            mealReplacementDO.setStartTime(date);
            mealReplacementDO.setEndTime(null);

            return mealReplacementService.save(mealReplacementDO);
        } else {
            MealReplacementDO mealReplacementDO = mealReplacementService.getOne(Wrappers.lambdaQuery(MealReplacementDO.class).eq(MealReplacementDO::getMachineId, personalOnlineStatusDTO.getMachineId()).eq(MealReplacementDO::getUserId, userId).eq(MealReplacementDO::getStatus, 1).orderByDesc(MealReplacementDO::getId).last("limit 1"));
            mealReplacementDO.setStatus(BooleanUtil.toInt(personalOnlineStatusDTO.getStatus()));
            mealReplacementDO.setEndTime(date);

            return mealReplacementService.updateById(mealReplacementDO);
        }
    }

    @Override
    public void delOperationUser(Long operationUserId, List<String> machines) {
        if (CollectionUtils.isEmpty(machines)) {
            return;
        }
        mealReplacementService.delOperationUser(operationUserId, machines);
    }


}
